package cn.getech.data.development.service.impl;

import cn.getech.data.development.constant.LastRunState;
import cn.getech.data.development.entity.JobDepHistory;
import cn.getech.data.development.entity.JobDepHistoryLogEntity;
import cn.getech.data.development.entity.ProcInfo;
import cn.getech.data.development.mapper.JobDepHistoryLogMapper;
import cn.getech.data.development.mapper.JobDepRunHistoryMapper;
import cn.getech.data.development.service.JobDepRunHistoryService;
import cn.getech.data.development.service.WorkFlowDepService;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.Query;
import cn.getech.system.center.model.dto.SysUserDto;
import cn.getech.system.center.service.SysUserService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 任务执行历史表 服务实现类
 * </p>
 *
 * @author zenith
 * @since 2018-08-27
 */
@Service
public  class JobDepHistoryServiceImpl extends ServiceImpl<JobDepRunHistoryMapper, JobDepHistory> implements JobDepRunHistoryService {

    @Autowired
    private JobDepRunHistoryMapper jobDepRunHistoryMapper;
    @Autowired
    private WorkFlowDepService workFlowDepService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JobDepHistoryLogMapper jobDepHistoryLogMapper;

    @Override
    public List<ProcInfo> logProcs(Integer type) {
        List<Integer> jobDepInfoIds = workFlowDepService.selectJobIds();
        if(CollectionUtil.isNotEmpty(jobDepInfoIds)){
            List<ProcInfo> procInfos = baseMapper.listDepJobs(jobDepInfoIds,type);
            if(CollectionUtil.isNotEmpty(procInfos)){
                return procInfos;
            }
        }
        return null;
    }

    @Override
    public List<Long> logUsers(Integer type) {
        //作业流
        List<Integer> jobDepInfoIds = workFlowDepService.selectJobIds();
        if(CollectionUtil.isNotEmpty(jobDepInfoIds)){
            List<Long> userInfos = baseMapper.logUsers(jobDepInfoIds,type);
            if(CollectionUtil.isNotEmpty(userInfos)){
                return userInfos;
            }
        }
        return null;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Object procIdObj = params.get("proc_id");

        List<Integer> jobDepInfoIds = null;
        if(null!= procIdObj){
            Integer proc_id =Integer.parseInt(procIdObj.toString());
            jobDepInfoIds = workFlowDepService.selectJobIdsByProcId(proc_id);
        } else {
            jobDepInfoIds = workFlowDepService.selectJobIds();
        }
        if (CollectionUtil.isNotEmpty(jobDepInfoIds)){
            params.put("jobDepInfoIds",jobDepInfoIds);
            IPage<JobDepHistory> page  = this.baseMapper.queryPage((Page<JobDepHistory>) new Query<JobDepHistory>().getPage(params),params);
            List<SysUserDto> userList = sysUserService.listAllUsers();
            Map<Long, String> userMap = userList.stream().collect(
                    Collectors.toMap(SysUserDto::getUserId, SysUserDto::getUsername));
            if (CollectionUtil.isNotEmpty(page.getRecords())) {
                for (JobDepHistory record : page.getRecords()) {
                    if (record.getCreatePer() != null) {
                        record.setCreatePerName(userMap.get(record.getCreatePer()));
                    }
                }
            }
            return new PageUtils(page);
        }else{
            return new PageUtils(null,0,0,0);
        }
    }

    @Override
    public List<JobDepHistory> getInfoByJobId(List<Integer> jobIds) {
        return jobDepRunHistoryMapper.getInfoByJobId(jobIds);
    }

    @Override
    public void removeLogicById(Integer id) {
        jobDepRunHistoryMapper.removeLogicById(id);
    }

    @Override
    public void moveLog(String endTime) {
        int currPage = 0;
        int limit = 500;
        Map<String,Object> params = new HashMap<>();
        params.put("endTime", endTime);
        params.put("offset", currPage * limit);
        params.put("limit", limit);
        List<Integer> idList = baseMapper.selectIdList(params);
        while (idList != null && idList.size() > 0){
            for(Integer id : idList){
                JobDepHistory jobDepHistory = baseMapper.selectById(id);
                if(jobDepHistory == null){
                    continue;
                }
                if(StringUtils.isEmpty(jobDepHistory.getLog()))
                    continue;

                JobDepHistoryLogEntity logEntity = new JobDepHistoryLogEntity();
                logEntity.setId(jobDepHistory.getId());
                JobDepHistoryLogEntity oldLog = jobDepHistoryLogMapper.selectById(logEntity.getId());
                if(oldLog == null)
                    jobDepHistoryLogMapper.insert(logEntity);
                else
                    jobDepHistoryLogMapper.updateById(logEntity);

                jobDepHistory.setLog("");
                baseMapper.updateById(jobDepHistory);
            }

            currPage++;
            params.put("offset", currPage * limit);
            idList = baseMapper.selectIdList(params);
        }
    }

    @Override
    public boolean saveOrUpdate2(JobDepHistory entity) {
        if(entity == null){
            return false;
        }
        JobDepHistoryLogEntity logEntity = null;
        if(!StringUtils.isEmpty(entity.getLog())){
            logEntity = new JobDepHistoryLogEntity();
            logEntity.setLog(entity.getLog());
            entity.setLog("");
        }

        if(null != entity && null != entity.getId()){
            JobDepHistory jobDepHistory = getById(entity.getId());
            //判断对象的字段是否超时
            if(null != jobDepHistory && Objects.equals(jobDepHistory.getIsOutHours(),1)){
                entity.setIsOutHours(1);
            }
            //判断是否是停止状态(则不修改)
            if(null != jobDepHistory && Objects.equals(jobDepHistory.getState(), LastRunState.STOP.getCode())){
                entity.setState(LastRunState.STOP.getCode());
            }
        }
        saveOrUpdate(entity);

        if(logEntity != null){
            JobDepHistory jobDepHistory = getOne(new QueryWrapper<JobDepHistory>().eq("job_dep_id",entity.getJobDepId()).eq("oozie_job_id",entity.getOozieJobId()));
            if(jobDepHistory == null){
                return false;
            }

            logEntity.setId(jobDepHistory.getId());
            JobDepHistoryLogEntity oldLog = jobDepHistoryLogMapper.selectById(logEntity.getId());
            if(oldLog == null)
                jobDepHistoryLogMapper.insert(logEntity);
            else
                jobDepHistoryLogMapper.updateById(logEntity);
        }
        return true;
    }

    @Override
    public String getLog(Integer id) {
        JobDepHistoryLogEntity oldLog = jobDepHistoryLogMapper.selectById(id);
        if(oldLog == null)
            return null;
        else
            return oldLog.getLog();
    }

}
